# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: shell_configparser.py 
@time: 2019/8/2 上午11:01
@note:
读取配置文件(*.ini *.conf ~/*.ini ~/*.conf )
"""
from configparser import ConfigParser
from sys import stdout
import logging
import logging.config

logging.config.fileConfig('logconfig.conf')
cfg = ConfigParser()

'读取配置文件名'
print(cfg.read('config.ini'))
'获取配置文件配置项'
print(cfg.sections())
logging.info('get all sections: %s', cfg.sections())
'获取installation所有key值'
print(cfg.options('installation'))
'获取library键值对'
print(cfg.items('installation'))
'获取配置项内容'
print('library =',cfg.get('installation', 'library'))
'获取配置项内容布尔值'
print('log_errors =', cfg.getboolean('debug', 'log_errors'))
'获取配置项内容整数'
print('port =', cfg.getint('server', 'port'))
'获取配置项内容长文本'
print('signature:\n', cfg.get('server','signature'))

'增加或修正配置项内容'
if 'mysql' not in cfg.sections(): cfg.add_section('mysql')
cfg.set('mysql', 'user', 'mysql')
cfg.set('mysql', 'password', '12345')
if 'kafka' not in cfg.sections(): cfg.add_section('kafka')
cfg.set('kafka', 'user', 'xiaoli')
cfg.set('server', 'port', '9000')
cfg.set('debug', 'log_errors', 'False')
cfg.write(stdout)
with open('config.ini', 'w+') as f:
    cfg.write(f)

'删除配置项内容或键值对'
cfg.remove_section('mysql')
cfg.remove_option('kafka', 'user')
cfg.remove_section('kafka')
cfg.write(stdout)
with open('config.ini', 'w+') as f:
    cfg.write(f)